package com.ophiux.cs.application.user.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ophiux.cs.application.core.AppResultCode;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.application.user.dto.AddUserPatientRequest;
import com.ophiux.cs.application.user.dto.AddUserPatientResponse;
import com.ophiux.cs.application.user.service.IAddUserPatientAppService;
import com.ophiux.cs.domain.user.model.aggregate.UserPatientInfo;
import com.ophiux.cs.domain.user.model.valueobj.PatientsValueObj;
import com.ophiux.cs.infrastructure.repositories.user.PatientRepository;
import com.ophiux.utils.common.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AddUserPatientAppService implements IAddUserPatientAppService{
	@Autowired
	PatientRepository patientRepository;
	@Override
	public Result<AddUserPatientResponse> AddUserPatient(AddUserPatientRequest dto) {
		AddUserPatientResponse resp = new AddUserPatientResponse();
		try {
			if(!dto.isParamValid()) {
				return Result.fail(AppResultCode.FAIL, ResultEnum.requestParamFail.getMsg());
			}                           
			
			UserPatientInfo userPatientInfo = patientRepository.getPatientsInfoList(new PatientsValueObj(dto.getUSER_ID()));
			if(userPatientInfo==null || StringUtil.isEmpty(userPatientInfo.getUSER_ID())) {
				return Result.fail(ResultEnum.NotFundUser);
			}
			
			Boolean IS_DEFAULT = dto.isDefault(dto.getIS_DEFAULT());
			String PatientId = userPatientInfo.addPatient(dto.getPATIENT_NAME(), dto.getBIRTH_DAY(), dto.getSEX(), dto.getPHONE(),dto.getCERTIFICATE_TYPE(),
					dto.getCERTIFICATE_NO(), dto.getADDRESS(), IS_DEFAULT);
			
			patientRepository.save(userPatientInfo);
			
			resp.setPATIENT_ID(PatientId);
		} catch (Exception e) {
			log.info("程序异常：",e);
			e.printStackTrace();
			return Result.fail(ResultEnum.requestException);
		}
		return Result.success(resp);
	}

}
